#include "precompiled.h"
#include "connector.h"
#include <QtNetwork>
#include "sslclient.h"
#include "connectorthread.h"

namespace Opl
{
	namespace Helpers
	{

		using Opl::Core::EntityObject;

		class ConnectorPrivate
		{
			public:
				ConnectorPrivate():
					status(Disconnected)
				{}
				~ConnectorPrivate() {}
				ConnectionStatus status;
				ConnectorSetup setup;
		};


		Connector::Connector(EntityObject* parent) :
			EntityObject(parent), O_PRIVATE_CREATE(Connector)
		{
			O_D(Connector);
			ConnectorThread::instance();
		}

		Connector::~Connector()
		{
			O_PRIVATE_DELETE;
		}

		void Connector::Setup(const ConnectorSetup& setup)
		{
			O_D(Connector);
			logger()->info("Connector::Setup");
			d->setup = setup;
			connect(ConnectorThread::instance(), SIGNAL(connected()), this, SLOT(threadConnected()));
			connect(ConnectorThread::instance(), SIGNAL(disconnected()), this, SLOT(threadDisconnected()));
			ConnectorThread::instance()->Setup(setup);
		}

		void Connector::Start()
		{
			O_D(Connector);
			logger()->info("Connector::Start");
			ConnectorThread::instance()->start();
		}

		void Connector::Stop(bool force/* = false*/)
		{
			O_D(Connector);
			logger()->info("Connector::Stop(force=%1)", force);

			if (ConnectorThread::instance()->isRunning()) {
				logger()->trace("ConnectorThread::isRunning");

				if (force) {
					ConnectorThread::instance()->terminate();

				} else {
					ConnectorThread::instance()->stop();
					ConnectorThread::instance()->wait();
				}
			}
		}

		void Connector::threadOutput(const QString& data)
		{
			emit output(data);
		}

		void Connector::threadConnected()
		{
			O_D(Connector);
			emit connected();
		}

		void Connector::threadDisconnected()
		{
			O_D(Connector);
			emit disconnected();
		}

		void Connector::Send(const QString& data)
		{
			O_D(Connector);
			ConnectorThread::instance()->Send(data);
		}

	}
}
